<template>
  <section>
    <div class="filter-container">
        <common-input @keyup.enter.native="handleFilter" class="w200" placeholder="活动名称" v-model="listQuery.name" />
        <el-select size="mini" v-model="listQuery.status" class="ml10" placeholder="活动状态" clearable>
            <el-option label="全部" value="0"></el-option>
            <el-option label="可用" value="1"></el-option>
            <el-option label="禁用" value="2"></el-option>
        </el-select>
        <el-button size="mini" class="ml10" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
        <el-button size="mini" class="ml10" @click="handleCreate" type="primary" icon="el-icon-plus">新增</el-button>
    </div>
    <el-table ref="dataTable" :height="tableHeight" :data="list"
                        @sort-change="tblSort"
                style="width: 100%">
            <el-table-column align="left" label="活动编号">
                <template slot-scope="scope">
                    <span>{{scope.row.id}}</span>
                </template>
            </el-table-column>
            <el-table-column align="left" label="活动名称">
                <template slot-scope="scope">
                    <span>{{scope.row.name}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="任务数量">
                <template slot-scope="scope">
                    <span>{{scope.row.itemCount}}</span>
                </template>
            </el-table-column>
            <el-table-column align="left" label="任务奖励">
                <template slot-scope="scope">
                    <span>{{scope.row.completeTypeText}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="活动状态">
                <template slot-scope="scope">
                    <span>{{scope.row.statusText}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="排序">
                <template slot-scope="scope">
                    <span>{{scope.row.orderNum}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="创建时间" width="150" sortable="custom" prop="created_at">
                <template slot-scope="scope">
                    <span>{{scope.row.createdAt}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作" 
                    fixed="right" v-if="!isSelect" width="130">
                <template slot-scope="scope">
                    <span>
                        <el-button type="text" @click="handleUpdate(scope.row)">编辑</el-button>
                        <el-button v-if="scope.row.canDelete==1" type="text" @click="handleDelete(scope.row)">删除</el-button>
                    </span>
                </template>
            </el-table-column>
    </el-table>
        <div class="pagination-container">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNum" :page-sizes="[20,30, 50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
        </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="900px">
        <el-form :model="form" :rules="rules" ref="form" label-width="150px">
            <el-form-item label="活动名称" prop="name">
                <common-input v-model="form.name" placeholder="请输入活动名称" />
            </el-form-item>
            <el-form-item label="选择任务">
                <el-button size="mini" class="ml10" @click="addItem()" type="primary" icon="el-icon-plus">选择任务</el-button>
                <table class="ikd-input-table ik-table-layout-fixed">
                    <thead>
                    <tr>
                        <th nowrap>序号</th>
                        <th nowrap>任务名称</th>
                        <th nowrap>奖励红包</th>
                        <th nowrap v-if="form.completeType==2">完成任务</th>
                        <th nowrap style="width:100px;">操作</th>
                    </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item, idx) in form.items" :key="item.id">
                            <td>{{idx+1}}</td>
                            <td>{{item.taskName}}</td>
                            <td>{{item.taskCoin}}</td>
                            <td v-if="form.completeType==2">
                                <el-checkbox v-model="item.inCompleteBool"></el-checkbox>
                            </td>
                            <td>
                                <el-button type="text"  @click="removeItem(idx)">删除</el-button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </el-form-item>
            <el-form-item label="完成奖励" prop="completeType">
                <el-radio-group v-model="form.completeType">
                    <el-radio v-for="item in complete_type_list" :key="item.value" :label="item.value">{{item.label}}</el-radio>
                </el-radio-group>
            </el-form-item>
            <template v-if="form.completeType>0">
                <el-form-item label="已选部分完成任务" v-if="form.completeType==2">
                    <table class="ikd-input-table ik-table-layout-fixed">
                        <thead>
                        <tr>
                            <th nowrap>序号</th>
                            <th nowrap>任务名称</th>
                            <th nowrap>奖励红包</th>
                        </tr>
                        </thead>
                        <tbody>
                            <template v-for="(item, idx) in form.items">
                                <tr v-if="item.inCompleteBool" :key="item.id">
                                    <td>{{idx+1}}</td>
                                    <td>{{item.taskName}}</td>
                                    <td>{{item.taskCoin}}</td>
                                </tr>
                            </template>
                        </tbody>
                    </table>
                </el-form-item>
                <el-form-item label="活动奖励">
                    <el-button size="mini" class="ml10" @click="handleProject()" type="primary" icon="el-icon-plus">选择项目</el-button>
                    <span style="color:red;margin-left:10px;">{{ form.projectDetail.name }}</span>
                </el-form-item>
            </template>
            <el-form-item label="排序" prop="orderNum">
                <common-input v-model="form.orderNum" class="w60" maxlength="3" />
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button size="mini" @click="dialogFormVisible=false">取消</el-button>
            <el-button size="mini" v-if="dialogStatus=='create'" type="primary" @click="create('form')">确定</el-button>
            <el-button size="mini" v-else type="primary" @click="update('form')">确定</el-button>
        </div>
    </el-dialog>

    <el-dialog title="选择任务" :visible.sync="dialogTaskVisible" :close-on-click-modal="false" width="1000px">
        <task-list :formData.sync="taskSelectForm" @okSelect="okSelectProduct" />
        <div slot="footer" class="dialog-footer">
            <el-button size="mini" type="primary" @click="dialogTaskVisible=false">关闭</el-button>
        </div>
    </el-dialog>

    <el-dialog title="选择项目" :visible.sync="dialogProjectVisible" :close-on-click-modal="false" width="1000px">
        <project-list :formData.sync="projectSelectForm" @okSelect="okSelectProject" />
        <div slot="footer" class="dialog-footer">
            <el-button size="mini" type="primary" @click="dialogProjectVisible=false">关闭</el-button>
        </div>
    </el-dialog>

  </section>
</template>

<script>
    import {
        isIntegerNotMust
    } from '../../utils/validator'
    import {
        task_activity_save,
        task_activity_list,
        task_activity_delete,
        task_activity_detail
    } from '../../api/product';
    import Viewer from 'viewerjs';
    import 'viewerjs/dist/viewer.css';
    export default {
        components: {
            'task-list': () => import('../../components/Product/task'),
            'project-list': () => import('../../components/Seller/project'),
        },
        props: {
            formData: Object
        },
        data() {
            return {
                projectSelectForm: {
                    is_select: true,
                    is_free: 1,
                },
                dialogProjectVisible: false,
                taskSelectForm: {
                    is_select: true,
                },
                dialogTaskVisible: false,
                status_list: [
                    {
                        value: 1,
                        label: '启用'
                    },
                    {
                        value: 0,
                        label: '禁用'
                    }
                ],
                complete_type_list: [
                    {
                        value: 0,
                        label: '无奖励'
                    },
                    {
                        value: 1,
                        label: '全部完成奖励'
                    },
                    {
                        value: 2,
                        label: '部分完成奖励'
                    },
                ],
                dialogProductVisible: false,
                productSelectForm: {
                    is_select: true,
                    is_sku: true,
                },
                rules: {
                    name: [
                        {
                            required: true,
                            message: '请输入活动名称',
                            trigger: 'blur'
                        }
                    ],
                    status: [
                        {
                            required: true,
                            message: '请选择活动状态',
                            trigger: 'blur'
                        }
                    ],
                    orderNum: [
                        {
                            validator: isIntegerNotMust,
                            trigger: 'blur'
                        }
                    ]
                },
                form: {
                    id: undefined,
                    name: undefined,
                    completeType: 0,
                    orderNum: undefined,
                    items: [],
                    completeProjectId: 0,
                    projectDetail: {
                        name: undefined,
                    }
                },
                dialogStatus: '',
                dialogFormVisible: false,
                textMap: {
                    update: '编辑活动',
                    create: '新增活动'
                },

                isSelect: false,
                viewerId: null,
                orderLoading: false,
                tableHeight: 200,
                list: null,
                listLoading: true,
                listQuery: {
                    pageNum: this.$route.query.pageNum || 1,
                    pageSize: this.$route.query.pageSize || 20,
                    name: this.$route.query.name,
                    orderCol: "",
                    orderAsc: "",
                    status: '0',
                    catId: "0",
                },
                total: null,
                activeName: '1',
                currentId: 0,
                checkLoading: false,
                dialogOrderVisible: false,
                orderForm: {
                    id: 0,
                    orderNum: 0,
                },
                productForm: {
                    id: 0,
                    hasSku: 0,
                    skuInfo: [],
                    inventory: 0,
                },
                dialogStockVisible: false,
                stockLoading: false,
                ids: [],
                selectedIdx: undefined,
            }
        },
        watch: {
            formData: {
                immediate: true,
                handler (val) {
                    this.isSelect = val.is_select;

                    // console.log(val)
                }
            }
        },
        mounted() {
            const that = this

            window.onresize = () => {

                return (() => {

                    that._getTableHeight()

                })()
            }
        },
        created() {
            this._getTableHeight();
            this.getList();
        },
        methods: {
            okSelectProject(item) {
                this.dialogProjectVisible = false;
                this.form.completeProjectId = item.id;
                this.form.projectDetail = item;
            },
            handleProject() {
                this.dialogProjectVisible = true;
            },
            addItem() {
                this.dialogTaskVisible = true;
            },
            removeItem(idx) {
                this.$confirm('确定删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        let final_items = [];
                        this.form.items.forEach((item, i)=>{
                            if(i != idx) {
                                final_items.push(item);
                            }
                        })

                        this.form.items = final_items;
                    }).catch(()=>{});
            },
            okSelectProduct(item) {
                this.dialogTaskVisible = false;
                if(!this.form.items) {
                    this.form.items = [];
                }
                let has = false;
                this.form.items.forEach((i)=>{
                    if(i.taskId == item.id) {
                        has = true;
                        return false;
                    }
                });

                if(!has) {
                    this.form.items.push(
                        {
                            id: undefined,
                            taskId: item.id,
                            taskName: item.name,
                            taskCoin: item.coin,
                        }
                    )
                }

            },
            handleCreate() {
                this.resetTemp();
                this.dialogStatus = 'create';
                this.dialogFormVisible = true;
            },
            create(formName) {
                const set = this.$refs;
                set[formName].validate(valid => {
                    if (valid) {
                        if(!this.form.orderNum) {
                            this.form.orderNum = 0;
                        }
                        task_activity_save(this.form)
                            .then(() => {
                                this.dialogFormVisible = false;
                                this.getList();
                                this.$message.success("活动创建成功");
                            })
                    } else {
                        return false;
                    }
                });
            },
            update(formName) {
                const set = this.$refs;
                set[formName].validate(valid => {
                    if (valid) {
                        if(!this.form.orderNum) {
                            this.form.orderNum = 0;
                        }

                        task_activity_save(this.form).then(() => {
                            this.dialogFormVisible = false;
                            this.getList();
                            this.$message.success("活动更新成功");
                        });
                    } else {
                        return false;
                    }
                });
            },
            resetTemp() {
                this.form = {
                    id: undefined,
                    name: undefined,
                    completeType: 0,
                    orderNum: undefined,
                    items: [],
                    completeProjectId: 0,
                    projectDetail: {
                        name: undefined,
                    },
                };
            },
            _getTableHeight() {
                this.tableHeight = window.innerHeight - 250
            },
            getList() {
                this.listLoading = true;
                task_activity_list(this.listQuery).then(response => {
                    this.list = response.data.list;
                    this.total = response.data.total;
                    this.listLoading = false;
                })
            },
            handleFilter() {
                this.listQuery.pageNum = 1;
                this.getList();
            },
            handleSizeChange(val) {
                this.listQuery.pageSize = val;
                this.getList();
            },
            handleCurrentChange(val) {
                this.listQuery.pageNum = val;
                this.getList();
            },
            handleClick(tab, event) {
                this.listQuery.status = this.activeName;
                this.handleFilter();
            // console.log(this.activeName)
            },
            leaveTab(activeName, oldActiveName) {
            // console.log(activeName)
            // return false;
            },
            handleUpdate(row) {
                task_activity_detail(row.id)
                    .then(response => {
                        this.form = response.data;
                        this.dialogFormVisible = true;
                        this.dialogStatus = 'update';
                    });
            },
            handleDelete(row) {
                this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        task_activity_delete(row.id)
                            .then(() => {
                                this.$message.success("活动删除成功");
                                this.getList();
                            });
                    }).catch(()=>{});
            },
            dialogClose() {
                this.$refs.form.resetFields();
            },
            tblSort(d) {
                this.listQuery.orderCol = d.prop;
                this.listQuery.orderAsc = d.order;

                this.handleFilter();
            },
        }
    };
</script>
<style lang="scss" scoped>
</style>
